package jmine.tec.rpc.common.serialization.json;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.text.ParseException;

import jmine.tec.json.JSONParser;
import jmine.tec.rpc.common.serialization.Serializer;
import jmine.tec.utils.io.ReversibleOutputStream;

/**
 * Serializer that uses JSON serialization.
 * 
 * @author lundberg
 */
public class JSONSerializer implements Serializer {

    private static final Charset ENCODING = Charset.forName("UTF-8");

    private JSONConverter converter;

    /**
     * {@inheritDoc}
     */
    public InputStream serialize(Object object) throws IOException {
        ReversibleOutputStream stream = new ReversibleOutputStream();
        this.converter.toJSON(object).write(new OutputStreamWriter(stream, ENCODING)).flush();
        return stream.reverse();
    }

    /**
     * {@inheritDoc}
     */
    public Object deserialize(InputStream stream) throws IOException, ParseException {
        return this.converter.toJava(JSONParser.fromReader(new InputStreamReader(stream, ENCODING)));
    }

    /**
     * @param converter the converter to set
     */
    public void setConverter(JSONConverter converter) {
        this.converter = converter;
    }
}
